package com.tchintech.pay.server;

import android.support.annotation.NonNull;


import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.CacheControl;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


import com.tchintech.pay.MyApplication;
import com.tchintech.pay.commod.BizInterface;
import com.tchintech.pay.utils.NetUtil;


import retrofit.GsonConverterFactory;

import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;



/**
 * <Pre>
 * 网络请求引擎类
 * </Pre>
 *
 * @author Freyrz
 * @version 1.0
 *          <p/>
 *          Create by 2016-05-19 10:33:39
 */
public class RetrofitService {

    //设缓存有效期为两天
    protected static final long CACHE_STALE_SEC = 60 * 60 * 24 * 2;
    //查询缓存的Cache-Control设置，为if-only-cache时只查询缓存而不会请求服务器，max-stale可以配合设置缓存失效时间
    protected static final String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=" + CACHE_STALE_SEC;
    //查询网络的Cache-Control设置，头部Cache-Control设为max-age=0时则不会使用缓存而请求服务器
    protected static final String CACHE_CONTROL_NETWORK = "max-age=0";

    private static OkHttpClient mOkHttpClient;

    public RetrofitService() {
    }

    private volatile  RetrofitService instance = null;

    public  RetrofitService getInstance() {
        if (instance == null) {
            synchronized (RetrofitService.class) {
                if (instance == null) {
                    instance = new RetrofitService();
                }
            }
        }
        return instance;
    }

    private volatile static ShowApi showApi = null;
    private volatile static CommitApi commitApi = null;
    private volatile  QueryApi queryApi=null;

    public  ShowApi createShowApi() {
        if (showApi == null) {
            synchronized (RetrofitService.class) {
                if (showApi == null) {
                    initOkHttpClient();
                    showApi = new Retrofit.Builder()
                            .client(mOkHttpClient)
                            .baseUrl(BizInterface.API)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .build().create(ShowApi.class);
                }
            }
        }
        return showApi;
    }
    public static CommitApi createCommitApi() {
        System.out.println(BizInterface.API);
        if (commitApi == null) {
            synchronized (RetrofitService.class) {
                if (commitApi == null) {
                    initOkHttpClient();
                    commitApi = new Retrofit.Builder()
                            .client(mOkHttpClient)
                            .baseUrl(BizInterface.API)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .build().create(CommitApi.class);
                }
            }
        }
        return commitApi;
    }

    public  QueryApi createQueryApi() {
        System.out.println(BizInterface.API);
        if (queryApi == null) {
            synchronized (RetrofitService.class) {
                if (queryApi == null) {
                    initOkHttpClient();
                    queryApi = new Retrofit.Builder()
                            .client(mOkHttpClient)
                            .baseUrl(BizInterface.API)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .build().create(QueryApi.class);
                }
            }
        }
        return queryApi;
    }

    // 配置OkHttpClient
    private static void initOkHttpClient() {
        if (mOkHttpClient == null) {
            // 因为BaseUrl不同所以这里Retrofit不为静态，但是OkHttpClient配置是一样的,静态创建一次即可
            File cacheFile = new File(MyApplication.getContext().getCacheDir(),
                    "HttpCache"); // 指定缓存路径
            Cache cache = new Cache(cacheFile, 1024 * 1024 * 1000); // 指定缓存大小1000Mb
            // 云端响应头拦截器，用来配置缓存策略
            Interceptor rewriteCacheControlInterceptor = new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    if (!NetUtil.isConnected(MyApplication.getContext())) {
                        request = request.newBuilder()
                                .cacheControl(CacheControl.FORCE_CACHE).build();
                        Logger.e("no network");
                    }
                    Response originalResponse = chain.proceed(request);
                    if (NetUtil.isConnected(MyApplication.getContext())) {
                        //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
                        String cacheControl = request.cacheControl().toString();
                        return originalResponse.newBuilder()
                                .header("Cache-Control", cacheControl)
                                .removeHeader("Pragma").build();
                    } else {
                        return originalResponse.newBuilder().header("Cache-Control",
                                "public, only-if-cached," + CACHE_STALE_SEC)
                                .removeHeader("Pragma").build();
                    }
                }
            };
            mOkHttpClient = new OkHttpClient();
            mOkHttpClient.setCache(cache);
            mOkHttpClient.networkInterceptors().add(rewriteCacheControlInterceptor);
            mOkHttpClient.interceptors().add(rewriteCacheControlInterceptor);
            mOkHttpClient.setConnectTimeout(10000, TimeUnit.SECONDS);


        }
    }

}
